package com.hero.jobweb.action.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.util.StrutsTypeConverter;

/**
 * 自定义日期装换器
 * 
 * @author Volcano
 * 
 */
public class DateConverter extends StrutsTypeConverter {
	private static final Log log=LogFactory.getLog(DateConverter.class);
	private static String DATE_FOMART[] = new String[] { "yyyy-MM-dd HH:mm:ss",
			"yyyy-MM", "yyyy-MM-dd" };

	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Date date = null;
		String dateString = null;
		if (!ArrayUtils.isEmpty(values)) {
			dateString = values[0];
		}
		if (!StringUtils.isEmpty(dateString)) {
			for (String fomartString : DATE_FOMART) {
				SimpleDateFormat format = new SimpleDateFormat(fomartString);
				try {
					if(log.isDebugEnabled())
					{
						log.info("正在尝试用"+fomartString+"装换日期");
					}
					date = format.parse(dateString);
					if(log.isDebugEnabled())
					{
						log.info("转换日期OK!");
						SimpleDateFormat successFormat = new SimpleDateFormat(DATE_FOMART[0]);
						log.info("转换之后的日期"+successFormat.format(date));
					}
					break;
				} catch (ParseException e) {
					log.info("转换日期失败!");
					date = null;
					continue;
				}
			}
		}
		return date;
	}

	@Override
	public String convertToString(Map context, Object o) {
		Date date = (Date) o;
		SimpleDateFormat format = new SimpleDateFormat(DATE_FOMART[2]);
		return format.format(date);
	}

}
